<template>
  <div>
    <div class="page-wrap">
      <div class="calendar-position">
        <el-calendar v-model="timeValue" @click="getTime(timeValue)">
          <template #date-cell="{ data }">
            <p class="selected">
            <!-- <p :class="data.isSelected ? 'is-selected' : ''"> -->
              <!-- {{ data.day.split('-').slice(1).join('-') }} -->
              {{data.day.split('-').slice(2).join('-')}}
              <!-- <span class="check-icon">{{ data.isSelected ? '*' : '' }}</span> -->
              <span class="check-icon">{{ resultTag(data.day) ? '*' : ''}}</span>
            </p>
          </template>
        </el-calendar>
        <div class="left-select">
          <el-select placeholder="康复师" v-model="query.train_doctor_id" clearable @clear="query.train_doctor_id = null" filterable @change="getTimeList">
            <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select placeholder="患者" v-model="query.trainers_id" filterable clearable @clear="query.trainers_id = null" @change="getTimeList">
            <el-option v-for="item in trainerList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select placeholder="场景" v-model="query.secens_id" filterable clearable @clear="query.secens_id = null" @change="getTimeList">
            <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="right-content">
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column prop="course_time_name" label="课程" align="center" width="120px">
            <template #default="scope">
              <span class="class-title">{{scope.row.course_time_name}}</span>
              <br/>
              <span class="class-time">{{scope.row.start_time}}-{{scope.row.end_time}}</span>
            </template>
          </el-table-column>
          <el-table-column :label="formatTime" align="center" width="val(100% - 20px)">
            <template #default="scope">
              <div>
              <div class="table-btn" v-if="scope.row.id == 0" @dblclick="addClass(scope.row, scope.$index+1)"></div>
              <div v-else  @dblclick="scope.row.course_status!= 2 ? addClass(scope.row, scope.$index+1) : null">
                <el-tooltip
                :disabled="scope.row.course_status == 2"
                effect="light"
                content="双击该行可重新编辑"
                placement="top"
              >
              <div class="content-course" :class="{'cursor-check': scope.row.course_status != 2}">
                <div>
                  <span v-if="scope.row.train_doctor_name">&nbsp;&nbsp;康复师:
                    <el-tag type="success">{{scope.row.train_doctor_name}}</el-tag>
                  </span>
                  <span v-if="scope.row.scens_name">&nbsp;&nbsp;训练场景:
                    <el-tag>{{scope.row.scens_name}}</el-tag></span>
                </div>
              </div>
                </el-tooltip>
              </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="right" width="450px">
            <template #default="scope">
              <div>
              <!-- <el-tooltip
                class="box-item"
                effect="light"
                content="开始训练"
                placement="top-start"
              > -->
              <el-button v-if="scope.row.course_status == 0 && scope.row.id != 0" type="success" @click.stop="execute(scope.row, 'start')">开始训练</el-button>
              <!-- </el-tooltip> -->
              <!-- <el-tooltip
                class="box-item"
                effect="light"
                content="重新训练"
                placement="top-start"
              > -->
               <el-button v-if="scope.row.course_status == 1 && scope.row.id != 0" type="success" @click.stop="execute(scope.row, 'start')">重新训练</el-button>
              <!-- </el-tooltip> -->
              <!-- <el-tooltip
                class="box-item"
                effect="light"
                content="停止训练"
                placement="top-start"
              > -->
              <el-button v-if="scope.row.course_status == 2 && scope.row.id != 0" type="warning" @click="execute(scope.row, 'stop')">停止训练</el-button>
              <!-- </el-tooltip> -->
              <!-- <el-tooltip
                class="box-item"
                effect="light"
                content="编辑"
                placement="top-start"
              > -->
              <el-button v-if="scope.row.course_status != 2 && scope.row.id != 0" type="info" @click="modify(scope.row)">编辑</el-button>
              <!-- </el-tooltip> -->
              <!-- <el-tooltip
                class="box-item"
                effect="light"
                content="查看进度"
                placement="top-start"
              > -->
              <!--   -->
              <el-button type="primary" v-if="scope.row.course_status == 2 && scope.row.id != 0" @click="process(scope.row)">进度</el-button>
              <!-- </el-tooltip> -->
              <!-- <el-tooltip
                class="box-item"
                effect="light"
                content="删除"
                placement="top-start"
              > -->
              <el-button v-if="scope.row.course_status != 2 && scope.row.id != 0" type="danger"  @click="del(scope.row)">删除</el-button>
              <!-- </el-tooltip> -->
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center" width="120px" fixed="right"></el-table-column> -->
        </el-table>
      </div>
    </div>
    <el-dialog
    v-model="visible" title="排课"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="cancelConfig">
      <div class="config-content">
        <div class="left-config">
          <el-form :model="configForm" ref="formRef" label-position="right" label-width="120px">
            <el-row>
              <el-col :span="12">
              <el-form-item prop="train_doctor_id" label="训练康复师" :rules="[{required: true, message:'请选择', trigger:'change'}]">
                <el-select placeholder="训练康复师" v-model="configForm.train_doctor_id" filterable clearable>
                  <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              </el-col>
            <!-- </el-row>
            <el-row> -->
             <el-col :span="12">
              <el-form-item prop="secens_id" label="场景" :rules="[{required: true, message:'请选择', trigger:'change'}]">
                <el-select placeholder="场景" v-model="configForm.secens_id" filterable clearable>
                  <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
              <el-form-item prop="course_date" label="时间" :rules="[{required: true, message:'请选择', trigger:'blur'}]">
                <el-date-picker
                  v-model="configForm.course_date"
                  disabled
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择时间"
                  style="width: 100%"
                  :clearable="false"
                  :editable="false"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-col>
            <!-- </el-row>
            <el-row> -->
            <el-col :span="12">
              <el-form-item prop="course_time_id" label="场数" :rules="[{required: true, message:'请选择', trigger:'change'}]">
                <el-select placeholder="上课时间场数" disabled v-model="configForm.course_time_id" filterable clearable @change="setRightClass">
                  <el-option v-for="item in tableData" :key="item.course_time_id" :label="item.course_time_name" :value="item.course_time_id">
                    <!-- {{item.course_time_name}}<span style="font-size:12px;color:#cbc;">&nbsp;{{item.start_time}}-{{item.end_time}}</span> -->
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
              <el-form-item prop="sound_bars" label="训练阶梯" :rules="[{required: true, message:'请输入', trigger:'blur'}]">
                <el-input-number style="width:100%" v-model="configForm.sound_bars" :min="1" :max="8"></el-input-number>
              </el-form-item>
              </el-col>
            <!-- </el-row>
            <el-row> -->
            </el-row>
            <el-row>
              <el-col :span="24">
               <el-form-item prop="trainers" label="参训人员" :rules="[{required: true, message:'请选择', trigger:'change'}]">
                <el-select placeholder="参训人员" v-model="configForm.trainers" multiple filterable clearable>
                  <el-option v-for="item in trainerList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveConfig(formRef)">保存</el-button>
          <el-button @click="cancelConfig">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 进度 -->
    <el-dialog
    v-model="processVisible" title="当前进度"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeProcess">
      <div class="demo-progress">
        <el-progress :percentage="processData" />
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import { CourseTimeService } from '@/api/service/courseTimeService';
import { DoctorService } from '@/api/service/doctorService';
import { TrainerService } from '@/api/service/trainerService';
import { ScenService } from '@/api/service/scenService';
import { VCourseSlotScensService } from '@/api/service/vCourseSlotScensService';
import { ElMessage, FormInstance, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs'
import circleUrl from '@/assets/img/img.jpg';

const timeValue = ref(new Date());
// const setData = ref([
//   {"date":"2025-07-29","tag": "*", "content":"放假"},
//   {"date":"2025-08-13","tag": "*", "content":"去交电费"},
//   {"date":"2025-08-14","tag": "*", "content":"去学习vue"}
// ])

let formatTime = ref(dayjs(new Date).format('YYYY-MM-DD'))
const getTime = (time) => {
  query.value.date = formatTime.value = dayjs(time).format('YYYY-MM-DD')
  getTimeList();
}

/**
  end_time: "8:45"
  id: 1
  name:"第一场"
  start_time:"8:00"
 */
const tableData = ref([]);
const currentTimeCourse = ref([])
let query = ref({
  date: formatTime.value,
  train_doctor_id: null,
  trainers_id: null,
  secens_id: null,
})
const getTimeList = async () => {
  const res = await VCourseSlotScensService.list(query.value);
  console.log('getTimeList=', res)
  currentTimeCourse.value = res
  tableData.value = res[0]?.content || []
}
getTimeList();

const train_doctor_id = ref();
const doctorList = ref([]);
const getDoctorList = async () => {
  const res = await DoctorService.list();
  doctorList.value = res;
};
getDoctorList();

const trainers = ref();
const trainerList = ref([]);
const getTrainerList = async () => {
  const res = await TrainerService.list();
  trainerList.value = res;
};
getTrainerList();

const scene = ref();
const sceneList = ref([]);
const getSceneList = async () => {
  const res = await ScenService.list();
  sceneList.value = res;
};
getSceneList();

const execute = async (row,type) => {
  if(type === 'start'){
    const res = await VCourseSlotScensService.start(row.id)
  }
  if(type === 'reset'){
    const res = await VCourseSlotScensService.start(row.id)
  }
  if(type === 'stop'){
    const res = await VCourseSlotScensService.stop(row.id)
  }
  ElMessage.success('已执行操作')
  getTimeList();
}
const formRef = ref<FormInstance>();
const visible = ref(false);
const cancelConfig = () => {
  visible.value = false;
  // formRef.value.resetFields();
}
const saveConfig = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return false;
    if(configForm.value.id == 0){
      const res = await VCourseSlotScensService.add(configForm.value)
    }
    if(configForm.value.id != 0){
      console.log('configForm.value==',configForm.value)
      const res = await VCourseSlotScensService.edit(configForm.value)
    }
    ElMessage.success('操作成功')
    cancelConfig();
    getTimeList();
  });
};
const addClass = (row, index) => {
  configForm.value = row
  if(!configForm.value.sound_bars){
    configForm.value.sound_bars = 1
  }
  visible.value = true;
}

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

const modify = (row) => {
    configForm.value = row
    if(!configForm.value.sound_bars){
      configForm.value.sound_bars = 1
    }
    visible.value = true;
}

const intervalId = ref(null)
const processVisible = ref(false)
const processData = ref(0)
const process = async(row) => {
  processData.value = await VCourseSlotScensService.getProcess(row.id)
  intervalId.value = setInterval(async () => {
    processData.value = await VCourseSlotScensService.getProcess(row.id)
  },10000)
  processVisible.value = true
}

const closeProcess = () => {
  clearInterval(intervalId.value)
  processVisible.value = false
}

const del = (row) => {
  ElMessageBox.confirm('是否确认删除当前排课？','提示',
    {
      confirmButtonText:'确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const res = await VCourseSlotScensService.del(row.id)
    ElMessage.success('删除成功')
    getTimeList();
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}


let configForm = ref({
  train_doctor_id: null,
  trainers: [],
  course_date: dayjs().format('YYYY-MM-DD'),
  course_time_id: null,
  sound_bars: 1,
  secens_id: null,
})

const setBeforeDay = () => {
  const currentDay = dayjs(configForm.value.course_date);
  // 获取前一天的日期
  const yesterday = currentDay.subtract(1, 'day');
  // 格式化为 YYYY-MM-DD 格式
  configForm.value.course_date = yesterday.format('YYYY-MM-DD');
}
const setAfterDay = () => {
  const currentDay = dayjs(configForm.value.course_date);
  // 获取前一天的日期
  const tomorrow = currentDay.add(1, 'day');
  // 格式化为 YYYY-MM-DD 格式
  configForm.value.course_date = tomorrow.format('YYYY-MM-DD');
}

const setRightClass = (id) => {
  
}

const resultTag = (day) => {
  let len = currentTimeCourse.value.length;
  let res = false
  for(let i = 0; i<len; i++ ){
    if(currentTimeCourse.value[i].data == day){
      res = true
      break;
    }
  }
  return res
}

const disabledDate = (time: Date) => {
  return time.getTime() < ((new Date()).getTime() - 1000 * 60 * 60 * 24)
}

</script>
<style scoped>
.page-wrap {
  display: flex;
  justify-content: space-between;
}

.right-content {
  width: calc(100% - 320px);
}

.class-title {
  font-size: 16px;
  font-weight: 600;
}

.class-time {
  color: #726a6ab4;
}

.left-select {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 0 10px 10px 10px;
  gap: 10px;
}

.doctor-item {
  display: flex;
  justify-content: start;
  align-items: center;
}

.table-btn {
  width: 100%;
  height: 64px;
  line-height: 64px;
  border-radius: 5px;
}
.table-btn:hover {
  border: 1px solid blue;
  cursor: pointer;
}
.table-btn:hover::after {
  content: '双击排课';
  display: flex;
  align-items: center;
  justify-content: center;
}

.config-content {
  display: flex;
  width: 100%;
  justify-content: space-between;
  min-height: 200px;
}
/* .h-flex {
  flex-grow: 1;
} */
.flex-1 {
 flex: 0 0 285px;
}

.left-config {
  /* border-right: 1px solid #cbcbcb; */
  margin-right: 5px;
  padding-right: 5px;
}
.right-table {
  width: 100%;
}
.config-item {
  font-size: 14px;
  color: #71ddc3;
}

.select-day {
  display: flex;
  justify-content: space-between;
  margin: 0 15% 10px 15%;
}

.before-day {
    border: 1px solid rgba(203, 203, 203, 0.8);
    padding: 2px;
    border-radius: 4px;
    cursor: pointer;
}

.show-day {
  font-size: 22px;
  user-select: none;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.content-course {
  display: flex;
  justify-content: space-between;
}
.cursor-check {
  cursor: pointer;
}

.right-content :deep(.el-table--border .el-table__cell) {
  border-right: 0px;
}

.del-btn {
  display: none;
}
.content-course:hover .del-btn {
  display: block;
}


.demo-progress .el-progress--line {
  margin-bottom: 15px;
  width: 350px;
}

</style>
<style>
.calendar-position {
  width: 300px;
  height: 300px;
}

.calendar-position .el-calendar__header {
  display: block;
}

.el-calendar {
  --el-calendar-cell-width: 30px;
}

.el-calendar__body {
  padding: 12px 20px 20px;
}
.selected {
  /* color: #1989fa; */
 position: relative;
}

.check-icon {
  color: red;
  /* color: #1989fa; */
  position: absolute;
  right: -5px;
  top: -5px;
}

</style>